// 购物车模块
import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useUserStore } from './user'
import { insertCartAPI, getNewCartListAPI, delCartAPI } from '@/apis/cart'

export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore()
  const isLogin = computed(()=> userStore.userInfo.token)
  const cartList = ref([])

  // 封装获取购物车列表
  const updateNewList = async () => {
    const res = await getNewCartListAPI()
    cartList.value = res.result
  }

    // 添加购物车
  const addCart = async (goods) => {
    // 判断是否登录
    const { skuId, count } = goods
    if (isLogin.value) {
      // 登录了
      await insertCartAPI({ skuId, count })
      updateNewList()
    } else {
      // 未登录
      // 已添加过 - count + 1 匹配传过来的商品对象中的skuId在cartList中能不能找到
    // 没添加过， push
    const item = cartList.value.find((item) => goods.skuId === item.skuId )
    if (item) {
      item.count++
    } else {
      cartList.value.push(goods)
    }
    }

    await ElMessage.success('添加成功')
  }

  

  // 删除购物车
  const delCart = async (skuId) => {
    if (isLogin.value) {
      // 登录了
      delCartAPI([skuId])
      updateNewList()
    } else {
      // 未登录
      // 思路.商品下标 splice
    const index = cartList.value.findIndex((item) => item.skuId === skuId)
    cartList.value.splice(index, 1)
    }
    
  }

  // 计算属性
  // 1.数量 count之和
  const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
  // 2.总价 price之和
  const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))
  // 3.已选择数量
  const selectedCount = computed(() => cartList.value.filter((item) => item.selected).reduce((a, c) => a + c.count, 0))
  // 4.已选择总价
  const selectedPrice = computed(() => cartList.value.filter((item) => item.selected).reduce((a, c) => a + c.count * c.price, 0))


  // 单选功能
  const singleCheck = (skuId, selected) => {
    // 通过skuId找到对应的商品对象
    const item = cartList.value.find((item) => item.skuId === skuId)
    item.selected = selected
  }

  // 是否全选
  const isAll = computed(() => cartList.value.every((item) => item.selected))
  // 全选功能
  const allCheck = (selected) => {
    cartList.value.forEach((item) => {
      item.selected = selected
    })
  }

  // 清除购物车
  const clearCart = () => {
    cartList.value = []
  }
  return {
    cartList,
    allCount,
    allPrice,
    isAll,
    selectedCount,
    selectedPrice,
    addCart,
    delCart,
    singleCheck,
    allCheck,
    clearCart,
    updateNewList
  }
},
{
 persist: true
}
)